<?php

namespace app\webapi\controller;

use app\common\service\OssSts;
use app\webapi\controller\AliSms;
use think\facade\Cache;
use think\facade\Config;
use think\facade\Db;
use think\facade\Env;
use think\facade\Request;
use dh2y\qrcode\QRcode;
//use app\controller\AliSms;
class ApiUser extends ApiBaseController
{
    /**
     * 登录
     */
    public function login()
    {
        $phone = Request::param('phone');
        $pwd = Request::param('pwd');
        $phone = preg_replace('/\s+/', '', $phone);
        if (!$phone) {
            $this->result_error('手机号不能为空');
        }
        if (!preg_match('/^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/', $phone)) {
            $this->result_error('手机号格式错误');
        }
        if (!$pwd) {
            $this->result_error('密码不能为空');
        }
        $user_info = Db::name('user')->where('phone', $phone)->find();
        if (empty($user_info)) {
            $this->result_error('用户不存在');
        }
        if ($user_info['state'] != 1) {
            $this->result_error('无法登录,联系管理员');
        }


        if ($user_info['pwd_md5'] === md5($pwd)) {
            if (!preg_match("/^[0-9]*$/", $user_info['id'])) {
                $this->result_error('用户id出错');
            }
            $token = $this->createToken($user_info['id']);
            $update_result = Db::name('user')->where('id', $user_info['id'])->update(['token' => $token, 'last_login_time' => $this->apiDate()]);
            if (!$update_result) {
                $this->result_error('登录失败');
            }
            $data = [
                'token' => $token,
                'nickname' => $user_info['nickname'],
                'phone' => $user_info['phone'],
                'avatar' => $user_info['avatar'],
                'qrcode' => $user_info['qrcode'],
                'payee_name' => $user_info['payee_name'],
                'payee_bankno' => $user_info['payee_bankno'],
                'payee_bankname' => $user_info['payee_bankname'],
                'wxpay_img' => $user_info['wxpay_img'],
                'alipay_img' => $user_info['alipay_img'],
                'has_sign' => $user_info['sign'] ? true : false,
                'has_read_protocol' => $user_info['has_read_protocol'],
                'edit_bank_access' => $user_info['edit_bank_access'],
                'edit_avatar_access' => $user_info['edit_avatar_access'],
                'edit_nickname_access' => $user_info['edit_nickname_access'],
                'level1_recommender' => $user_info['level1_recommender'],
                'address_list' => $user_info['address_list'] ?? [],
                'create_time' => $user_info['create_time'],
                'last_login_time' => $user_info['last_login_time'],
                'open_id' => $user_info['open_id']
            ];
            unset($user_info['pwd_md5']);
            unset($user_info['admin_pwd']);
            $user_info['roles'] = is_string($user_info['roles'])?json_decode($user_info['roles'], true):$user_info['roles'];
            $alist = Db::name('user_address')->where('uid', $user_info['id'])->select()->toArray();
            $user_info['address_list'] = $alist;
            $user_info['token'] = $token;
            $data['roles'] = $user_info['roles'];
            // 使用Redis缓存
//            Cache::store('redis')->set(self::KEYS['TOKEN'] . $user_info['id'], json_encode($user_info), 86400 * 365);
            APiRedisServer::selected(1)->setex(self::KEYS['TOKEN'] . $user_info['id'],  86400 * 365,json_encode($user_info));
            $this->result_ok('登录成功', $data);
        }
        $this->result_error('密码错误');

    }

    /**
     * 检查注册信息
     */
    public function checkInfo()
    {
        $nickname = Request::param('nickname');
        // if (!preg_match('/^[\u4E00-\u9FA5A-Za-z0-9]+$/', $nickname)) {
        //     $this->result_error('用户名只能为数字字母和汉字');
        // }
        if (strlen($nickname) > 25) {
            $this->result_error('用户名长度应小于25');
        }
        if (empty($nickname)) {
            $this->result_error('昵称不能为空');
        }
        if (!preg_replace('/\s*/', '', $nickname)) {
            $this->result_error('昵称不能为空');
        }
        $phone = Request::param('phone');
        $phone = preg_replace('/\s+/', '', $phone);
        if (!$phone) {
            $this->result_error('手机号不能为空');
        }
        if (!preg_match('/^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/', $phone)) {
            $this->result_error('手机号格式错误');
        }
        $sql_result = Db::name('user')->where('phone', $phone)->find();
        if (!empty($sql_result)) {
            $this->result_error('手机号已被占用');
        }

        $sql_result = Db::name('user')->where('nickname', $nickname)->find();
        if (!empty($sql_result)) {
            $this->result_error('用户名重复!');
        }
        $this->result_ok('可以注册');
    }

    /** 重新生成二维码 */
    public function qrAgain()
    {
        $sql_result = 362235;
        $qr_data = Env::get('app.fronthost') . '?rid=' . $sql_result;
        //生成二维码
        $qrCode = new QRcode();
        $path = "./uploads/qrcode/" . $sql_result . ".png";
        if(!is_dir("uploads/qrcode/")){
            mkdir(iconv("UTF-8", "GBK","./uploads/qrcode/"),0777,true);
        }
        $qrCode->png($qr_data, $path, 10, "H");
        $oss = ApiOss::getClient()->uploadFile('luxiaxe','qr-code/' .$sql_result .'_qr_'.time().'.jpg',app()->getRootPath().'public/uploads/qrcode/'.$sql_result . ".png");

        Db::name('user')->where('id', $sql_result)->update(['qrcode' => $oss['info']['url']??'']);
    }

    /**
     * 用户注册
     */
    public function register()
    {
        $nickname = Request::param('nickname');
        $phone = Request::param('phone');
        $sms_code = Request::param('sms_code');
        $pwd = Request::param('pwd');
        $rid = (int)Request::param('rid');
        $open_id = (int)Request::param('open_id');
        // if (!preg_match('/^[\u4E00-\u9FA5A-Za-z0-9]+$/', $nickname)) {
        //     $this->result_error('用户名只能为数字字母和汉字');
        // }
        if (strlen($nickname) > 25) {
            $this->result_error('用户名长度应小于25');
        }
        if (empty($nickname)) {
            $this->result_error('昵称不能为空');
        }
        if (!preg_replace('/\s*/', '', $nickname)) {
            $this->result_error('昵称不能为空');
        }
        if (!$phone) {
            $this->result_error('手机号不能为空');
        }
        if (empty($sms_code)) {
            $this->result_error('请填写验证码');
        }
        if (empty($pwd)) {
            $this->result_error('密码不能为空');
        }
        if (!preg_match('/^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/', $phone)) {
            $this->result_error('手机号格式错误');
        }
        $sql_result = Db::name('user')->where('phone', $phone)->find();
        if (!empty($sql_result)) {
            $this->result_error('手机号已被占用');
        }

        $sql_result = Db::name('user')->where('nickname', $nickname)->find();
        if (!empty($sql_result)) {
            $this->result_error('用户名重复!');
        }

        if (!$open_id) {
            $open_id = "";
        }
        $check = ApiSms::checkSMScode($phone, $sms_code);
        if (!$check) {
            $this->result_error('验证码不正确');
        }
        /**
         * 获取推荐关系
         */
        $rData = funcGetAllLevelRecommender($rid);

        // 启动事务
        Db::startTrans();
        try {
            $insert = array(
                'phone' => $phone,
                'nickname' => $nickname,
                'avatar' => "",
                'pwd_md5' => md5($pwd),
                'recommender_path' => $rData['path'],
                'level1_recommender' => $rData['level1'],
                'level2_recommender' => $rData['level2'],
                'edit_bank_access' => 1,
                'bucket_id' => $rData['bucket_id'],
                'open_id' => $open_id
            );
            $sql_result = Db::name('user')->insertGetId($insert);
            if ($sql_result > 0) {
                $qr_data = Env::get('app.fronthost') . '?rid=' . $sql_result;
                //生成二维码
                $qrCode = new QRcode();
                $path = "./uploads/qrcode/" . $sql_result . ".png";
                if(!is_dir("uploads/qrcode/")){
                    mkdir(iconv("UTF-8", "GBK","./uploads/qrcode/"),0777,true);
                }
                $qrCode->png($qr_data, $path, 10, "H");
                $oss = ApiOss::getClient()->uploadFile('luxiaxe','qr-code/' .$sql_result .'_qr_'.time().'.jpg',app()->getRootPath().'public/uploads/qrcode/'.$sql_result . ".png");
                Db::name('user')->where('id', $sql_result)->update(['qrcode' => $oss['info']['url']??'']);
            }
            // 如果推荐人有分仓，直接进分仓
            if ($rData['bucket_id'] > 0) {
                $bdata = Db::name('user_bucket')->where('id', $rData['bucket_id'])->find();
                if (!empty($bdata)) {
                    $members = json_decode($bdata['members'], true);
                    Db::name('user_bucket')->where('id', $rData['bucket_id'])->update(['members' => json_encode($members)]);
                }
            }
            // 提交事务
            Db::commit();
            $this->result_ok('注册成功');
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            $this->result_error('注册失败'.$e->getMessage());
        }


    }

    /**
     * 获取用户信息
     */
    public function getInfo()
    {
        $user_info = $this->checkToken();
//        $data = [
//            'token' => $user_info['token'],
//            'nickname' => $user_info['nickname'],
//            'phone' => $user_info['phone'],
//            'avatar' => $user_info['avatar'],
//            'qrcode' => $user_info['qrcode'],
//            'payee_name' => $user_info['payee_name'],
//            'payee_bankno' => $user_info['payee_bankno'],
//            'payee_bankname' => $user_info['payee_bankname'],
//            'wxpay_img' => $user_info['wxpay_img'],
//            'alipay_img' => $user_info['alipay_img'],
//            'has_sign' => $user_info['sign'] ? true : false,
//            'has_read_protocol' => $user_info['has_read_protocol'],
//            'edit_bank_access' => $user_info['edit_bank_access'],
//            'edit_avatar_access' => $user_info['edit_avatar_access'],
//            'edit_nickname_access' => $user_info['edit_nickname_access'],
//            'level1_recommender' => $user_info['level1_recommender'],
//            'address_list' => $user_info['address_list'],
//            'create_time' => $user_info['create_time'],
//            'last_login_time' => $user_info['last_login_time'],
//            'roles' => $user_info['roles'],
//            'open_id' => $user_info['open_id']
//        ];
        $data = $user_info;
        $alist  = Db::name('user_address')->where('uid',$user_info['id'])->select()->toArray();
        $data['address_list'] = $alist;
        $data['has_sign'] = (bool)$data['sign'];
        unset($user_info['pwd_md5']);
        unset($user_info['admin_pwd']);
//        $data['roles'] = $data['roles'];
//        $sql_result = Db::name('user')->where('phone', $user_info['phone'])->field('id')->find();
//        if ($sql_result['id'] > 0) {
//            $qr_data = Config::get('app.app_host') . '?rid=' . $sql_result['id'];
//            //生成二维码
//            $qrCode = new QRcode();
//            $path = "uploads/qrcode/" . $sql_result['id'] . ".png";
//            $qrCode->png($qr_data, $path, 8, "L");
//            Db::name('user')->where('id', $sql_result['id'])->update(['qrcode' => Config::get('app.app_host') . '/' . $path]);
//        } else {
//            $this->result_error("用户ID出错");
//        }
        $this->result_ok("ok", $data);

    }

    /**
     * 修改昵称
     */
    public function editNickname()
    {
        $user_info = $this->checkToken();
        $nickname = Request::param('nickname');
//        if (!preg_match('/^[\u4E00-\u9FA5A-Za-z0-9]+$/', $nickname)) {
//            $this->result_error('用户名只能为数字字母和汉字');
//        }
        if (strlen($nickname) > 25) {
            $this->result_error('用户名长度应小于25');
        }
        if (empty($nickname)) {
            $this->result_error('昵称不能为空');
        }
        if (!preg_replace('/\s*/', '', $nickname)) {
            $this->result_error('昵称不能为空');
        }
        if (!preg_match('/^\d+$/', $user_info['id'])) {
            $this->result_error('用户id出错');
        }
        $data = Db::name('user')->where('nickname', $nickname)->find();
        if (!empty($data)) {
            $this->result_error("昵称已被占用");
        }
        $up_res = Db::name('user')->where('id', $user_info['id'])->update([
            'nickname' => $nickname
        ]);
        if ($up_res) {
//            信息更新到redis
            $this->updateUserInfo($user_info['id']);
            $this->result_ok("修改成功");
        } else {
            $this->result_error("更新失败");
        }
    }

    /**
     * 修改头像先不写
     */
    public function editAvatar()
    {
        $user_info = $this->checkToken();
        $avatar = Request::param('avatar');
        if(empty($avatar)){
            $this->result_error("头像不能为空");
        }
        $up_res = Db::name('user')->where('id',$user_info['id'])->update(['avatar'=>$avatar]);
        if($up_res){
            $this->updateUserInfo($user_info['id']);
            $this->result_ok("修改成功");
        }
        $this->result_error("修改失败");
    }

    /**
     * 上传微信收款码/支付宝收款
     */
    public function editReceiptCode()
    {
        $user_info = $this->checkToken();
        $imgUrl = Request::param('imgUrl');
        $type = Request::param('type');
        if (empty($imgUrl)) {
            $this->result_error("收款码不能为空");
        }
        if (!preg_replace('/\s*/g', '', $imgUrl)) {
            $this->result_error('收款码不能为空');
        }
        if (empty($type)) {
            $this->result_error("请选择当前收款码的类型");
        }
        if (!in_array($type, ['wxpay_img', 'alipay_img'])) {
            $this->result_error("收款码类型无效");
        }
        if (!preg_match("/^[0-9]*$/", $user_info['id'])) {
            $this->result_error('用户id出错');
        }
        $up_res = Db::name('user')->where('id', $user_info['id'])->update([$type => $imgUrl]);
        if ($up_res) {
            $this->result_ok("修改成功");
        } else {
            $this->result_error("修改失败");
        }

    }

    /**
     * 刷新token 目前看没人调用  没吊用
     */
    public function refreshToken()
    {
        $user_info = $this->checkToken();
        if (!preg_match("/^[0-9]*$/", $user_info['id'])) {
            $this->result_error('用户id出错');
        }
        $token = $this->createToken($user_info['id']);
        $update_result = Db::name('user')->where('id', $user_info['id'])->update(['token' => $token, 'last_login_time' => $this->apiDate()]);
//        $info = Cache::store('redis')->get(self::KEYS['TOKEN'] . $user_info['id']);
        $info = APiRedisServer::selected(1)->get(self::KEYS['TOKEN'] . $user_info['id']);
        if (!empty($info)) {
            $info = json_decode($info, true);
            $info['token'] = $token;
//            Cache::store('redis')->set(self::KEYS['TOKEN'] . $user_info['id'], json_encode($user_info), 86400 * 10);
            APiRedisServer::selected(1)->setex(self::KEYS['TOKEN'] . $user_info['id'], 86400 * 10, json_encode($user_info));
        }
        $this->result_ok("ok", $token);
    }

    /**
     * 修改密码
     */
    public function resetPwd()
    {
        $user_info = $this->checkToken();
        $cur_pwd = Request::param('cur_pwd');
        $new_pwd = Request::param('new_pwd');
        if (empty($cur_pwd) || empty($new_pwd)) {
            $this->result_error("密码不能为空");
        }
        if ($cur_pwd == $new_pwd) {
            $this->result_error("新密码不能与原密码相同");
        }
        if (!preg_match("/^[0-9]*$/", $user_info['id'])) {
            $this->result_error('用户id出错');
        }
        $uinfo = Db::name('user')->where('id', $user_info['id'])->find();
        if (md5($cur_pwd) != $uinfo['pwd_md5']) {
            $this->result_error("原密码验证失败");
        }
        $up_res = Db::name('user')->where('id', $user_info['id'])->update(['pwd_md5' => md5($new_pwd), 'token' => 'pwd reset']);
        if ($up_res) {
            $this->result_ok("修改密码成功");
        } else {
            $this->result_error("修改密码失败");
        }
    }

    /**
     * 重置密码
     */
    public function resetPwdSmsCode()
    {
        $phone = Request::param('phone');
        $sms_code = Request::param('sms_code');
        $new_pwd = Request::param('new_pwd');
        if (!$phone) {
            $this->result_error('手机号不能为空');
        }
        if (!preg_match('/^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/', $phone)) {
            $this->result_error('手机号格式错误');
        }
        if (!$new_pwd) {
            $this->result_error('密码不能为空');
        }
        if (empty($sms_code)) {
            $this->result_error('验证码不能为空');
        }
        $check = ApiSms::checkSMScode($phone, $sms_code);
        if (!$check) {
            $this->result_error('验证码不正确');
        }
        $sql_result = Db::name('user')->where('phone', $phone)->find();
        if (empty($sql_result)) {
            $this->result_error('用户不存在,请注册');
        }
        $user_info = $sql_result;
        if (!preg_match("/^[0-9]*$/", $user_info['id'])) {
            $this->result_error('用户id出错');
        }
        $up_res = Db::name('user')->where('id', $user_info['id'])->update(['pwd_md5' => md5($new_pwd), 'token' => 'pwd reset']);
        if ($up_res) {
            $this->result_ok("密码重置成功,请重新登录");
        } else {
            $this->result_error("密码重置失败");
        }
    }

    /**
     * 更新用户信息(包括昵称/银行卡信息)
     */
    public function updateUserInfoAPI()
    {
        $user_info = $this->checkToken();
        $nickname = Request::param('nickname');
        $avatar = Request::param('avatar');
        $gender = (int)(Request::param('gender'));
        $email = Request::param('email');
        $payee_name = Request::param('payee_name');
        $payee_bankno = Request::param('payee_bankno');
        $payee_bankname = Request::param('payee_bankname');
        $wxpay_img = Request::param('wxpay_img');
        $alipay_img = Request::param('alipay_img');
        $edit_bank_access = Request::param('edit_bank_access');
        $sign = Request::param('sign');
        $has_read_protocol = (int)(Request::param('has_read_protocol'));

        $updataArray = array();
        if (preg_match('/^[\u4E00-\u9FA5A-Za-z0-9]+$/', $nickname) && strlen($nickname) > 25) {
            $updataArray['nickname'] = $nickname;
        }
        if (!empty($avatar)) {
            $updataArray['avatar'] = $avatar;
        }
        if (in_array($gender, [0, 1, 2])) {
            $updataArray['gender'] = $gender;
        }
        if (!empty($email)) {
            $updataArray['email'] = $email;
        }
//        var_dump($edit_bank_access);die;
        if (!is_null($edit_bank_access)&& ($edit_bank_access == 0 || $edit_bank_access == 1)) {
            if (strlen($payee_name) > 0 && strlen($payee_name) <= 10) {
                if (preg_match('/^[\x{4e00}-\x{9fa5}]+$/u', $payee_name)) {
                    $updataArray['payee_name'] = $payee_name;
                } else {
                    $this->result_error("请输入正确的姓名");
                }
            } else {
                $this->result_error("请输入正确的姓名");
            }
            if (strlen($payee_bankno) > 0) {
                if (preg_match('/^([1-9]{1})(\d{15}|\d{16}|\d{18})$/', $payee_bankno)) {
                    $updataArray['payee_bankno'] = $payee_bankno;
                } else {
                    $this->result_error("请输入正确的银行卡号");
                }
            } else {
                $this->result_error("请输入正确的银行卡号1");
            }
            if (strlen($payee_bankname) > 0 && strlen($payee_bankname) <= 100) {
                if (preg_match('/^[\x{4e00}-\x{9fa5}]+$/u', $payee_bankname)) {
                    $updataArray['payee_bankname'] = $payee_bankname;
                } else {
                    $this->result_error("请输入正确的开户行1");
                }
            } else {
                $this->result_error("请输入正确的开户行2");
            }
        }
        if (!empty($wxpay_img)) {
            $updataArray['wxpay_img'] = $wxpay_img;
        }
        if (!empty($alipay_img)) {
            $updataArray['alipay_img'] = $alipay_img;
        }
        if (!empty($sign)) {
            $updataArray['sign'] = $sign;
        }
        if ($has_read_protocol == 1) {
            $updataArray['has_read_protocol'] = $has_read_protocol;
        }
        $sql_result = Db::name('user')->where('id', $user_info['id'])->update($updataArray);
        if ($sql_result) {
            $this->updateUserInfo($user_info['id']);
            $this->result_ok("更新成功");
        } else {
            $this->result_ok("没有要更新的信息");
        }

    }

    /**
     * 获取粉丝数据信息
     */
    public function getFansDataInfo()
    {
        $user_info = $this->checkToken();
        $data = Db::name('user')
            ->whereRaw("level1_recommender={$user_info['id']} OR level2_recommender={$user_info['id']}")
            ->field('id,create_time')
            ->order('id', 'desc')
            ->select()->toArray();
        $tadaydata = 0;
        foreach ($data as $v) {
            if ($v['create_time'] > date("Y-m-d 00:00:00", time())) {
                $tadaydata++;
            }
        }
        $this->result_ok('ok', ['today_count' => $tadaydata, 'total_count' => count($data)]);

    }

    /**
     * 获取粉丝列表
     */
    public function getFansList()
    {
        $user_info = $this->checkToken();
//        $user_info['id'] = 3850;
        $level = Request::param('level');
        $page_size = (int)Request::param('page_size');
        $page_index = (int)Request::param('page_index');
        if ($level != 1 && $level != 2) {
            $this->result_error("粉丝等级参数错误");
        }
        if ($page_size < 1 ) {
            $this->result_error("分页参数错误", ['page_index' => $page_index, 'page_size' => $page_size]);
        }
        $limit = $page_index  * $page_size;
        if ($level == 1) {
            $sql_result = Db::name('user')->where('level1_recommender', $user_info['id'])->field('nickname,avatar,phone,create_time')->limit($limit, $page_size)->select()->toArray();
//            var_dump(Db::name('user')->getLastSql());
            $sql_count_result = Db::name('user')->where('level1_recommender', $user_info['id'])->count();
        } else {
            $sql_result = Db::name('user')->where('level2_recommender', $user_info['id'])->field('nickname,avatar,phone,create_time')->limit($limit, $page_size)->select()->toArray();
            $sql_count_result = Db::name('user')->where('level2_recommender', $user_info['id'])->count();
        }
//        var_dump($sql_result);
//        var_dump($sql_count_result);
        $data = array(
            'page_index' => $page_index,
            'page_size' => $page_size,
            'total_count' => $sql_count_result,
            'list' => $sql_result
        );
        $this->result_ok('ok', $data);

    }

    /**
     * 获取粉丝订单
     */
    public function getFansOrder()
    {
        $user_info = $this->checkToken();
        $page_size = (int)Request::param('page_size');
        $page_index = (int)Request::param('page_index');
        if ($page_size < 1 ) {
            $this->result_error("分页参数错误", ['page_index' => $page_index, 'page_size' => $page_size]);
        }
        $limit = $page_index * $page_size;
        $sql = "SELECT a.order_no,c.fans_uid,c.income,c.rate,b.nickname fans_nickname,b.avatar fans_avatar,d.name goods_name,d.img goods_img,d.code,d.id,
        a.g_price,b.level1_recommender,b.level2_recommender,a.pay_state,e.nickname saler_nickname
        FROM sy_user_order a
        INNER JOIN sy_user b ON a.uid=b.id
        LEFT JOIN sy_user_income_record c ON c.order_id=a.id AND c.uid=a.uid
        LEFT JOIN sy_goods_rush d ON d.id=a.gid
        LEFT JOIN sy_user e ON e.id=a.saler_id
        WHERE a.pay_state>-1 AND a.state=1 AND (b.level1_recommender=? OR b.level2_recommender=?)
        ORDER BY a.create_time DESC
        LIMIT ?,?";
        $sql_result = Db::query($sql, [$user_info['id'], $user_info['id'], $limit, $page_size]);
        $sql_count = "SELECT COUNT(*) total_count FROM sy_user_order a INNER JOIN sy_user b ON a.uid=b.id WHERE a.pay_state>-1 AND a.state=1 AND (b.level1_recommender=? OR b.level2_recommender=?)";
        $sql_count_result = Db::query($sql_count, [$user_info['id'], $user_info['id']]);
//        var_dump($sql_result);
//        var_dump($sql_count_result);
        $list = $sql_result;

        //获取收益率
        $rates = Db::name('other_config')->whereIn('id', '2,3')->select()->toArray();
        $r1 = 0;
        $r2 = 0;
        foreach ($rates as $v) {
            if ($v['id'] == 2) {
                $r1 = (int)$v['value3'];
            } elseif ($v['id'] == 3) {
                $r2 = (int)$v['value3'];
            }
        }
        foreach ($list as &$v) {
            if ($v['level1_recommender'] == $user_info['id']) {
                $v['level'] = 1;
                if (empty($v['income'])) { // 如果是没有确认收款的订单，实际上没有产生收益记录，此时实时计算
                    $v['income'] = (int)($v['g_price'] * $r1 * 0.001);
                }
            } elseif ($v['level2_recommender'] == $user_info['id']) {
                $v['level'] = 2;
                if (empty($v['income'])) {// 如果是没有确认收款的订单，实际上没有产生收益记录，此时实时计算
                    $v['income'] = (int)($v['g_price'] * $r2 * 0.001);
                }
            }
            unset($v['level1_recommender']);
            unset($v['level2_recommender']);
            if ($v['pay_state'] == 0) {
                $v['stateStr'] = "待付款";
            } else if ($v['pay_state'] == 1) {
                $v['stateStr'] = "已付款";
            } else if ($v['pay_state'] == 2) {
                $v['stateStr'] = "已上架";
            }
        }
        $data = array(
            'page_index' => $page_index,
            'page_size' => $page_size,
            'total_count' => $sql_count_result[0]['total_count'],
            'list' => $list
        );
        $this->result_ok('ok', $data);
    }

    /**
     * 获取粉丝订单统计数据
     */
    public function getFansOrderInfo()
    {
        $user_info = $this->checkToken();
        $sql = "SELECT * FROM sy_user_order a 
                INNER JOIN sy_user b ON a.uid=b.id 
                WHERE (b.level1_recommender=? OR b.level2_recommender=?) AND a.pay_state>-1 AND a.state=1";
        $sql_result = Db::query($sql, [$user_info['id'], $user_info['id']]);
        $data = array(
            'orders_total_price' => 0,
            'orders_total_count' => 0,
        );
        if (count($sql_result) > 0) {
            $data['orders_total_count'] = count($sql_result);
        }
        $sql1 = "SELECT SUM(a.g_price) orders_total_price FROM sy_user_order a INNER JOIN sy_user b ON a.uid=b.id WHERE (b.level1_recommender=? OR b.level2_recommender=?) AND a.pay_state>-1 AND a.state=1";
        $sql_result1 = Db::query($sql1, [$user_info['id'], $user_info['id']]);
        if (count($sql_result1) > 0) {
            $data['orders_total_price'] = $sql_result1[0]['orders_total_price'];
        }
        $this->result_ok('ok', $data);
    }

    /**
     * 退出登录
     */
    public function logout()
    {
        $user_info = $this->checkToken();
        $res = Db::name('user')->where('id', $user_info['id'])->update(['token' => "logout"]);
        if ($res) {
            $this->result_ok('ok');
        }
        $this->result_ok("用户Id出错");
    }

    /**
     * 获取推荐人信息
     */
    public function whoIsRecommender()
    {
        $rid = (int)Request::param('rid');
        if (!($rid > 0)) {
            $this->result_ok('ok', ['rid' => 0, 'rname' => '无']);
        }
        $sql_result = Db::name('user')->where('id', $rid)->field('avatar,nickname,phone')->find();
        if (!empty($sql_result)) {
            $this->result_ok('ok', [
                'rid' => $rid,
                'rname' => $sql_result['nickname'],
                'rphone' => $sql_result['phone'],
                'ravatar' => $sql_result['avatar']
            ]);
        }
        $this->result_ok('ok', ['rid' => 0, 'rname' => '无']);
    }

    /**
     *修改用户open_id
     */
    public function updateOpenId()
    {

    }
    /**
     * 获取我的订单
     */
    public function getMyOrder(){
        $user_info = $this->checkToken();
        $page_size = (int)Request::param('page_size');
        $page_index = (int)Request::param('page_index');
        if ($page_size < 1 ) {
            $this->result_error("分页参数错误", ['page_index' => $page_index, 'page_size' => $page_size]);
        }
        $limit = $page_index * $page_size;
//        $sql = "SELECT a.order_no,d.name goods_name,d.img goods_img,d.code,d.id,
//        a.g_price,a.pay_state,e.nickname saler_nickname
//        FROM sy_user_order a
//        LEFT JOIN sy_goods_rush d ON d.id=a.gid
//        LEFT JOIN sy_user e ON e.id=a.saler_id
//        WHERE a.pay_state>-1 AND a.state=1 AND a.uid=?
//        ORDER BY a.create_time DESC
//        LIMIT ?,?";
        $sql = "SELECT a.order_no,d.name goods_name,d.img goods_img,d.code,d.id,
        a.g_price,a.pay_state,a.state as astate,e.nickname saler_nickname
        FROM sy_user_order a
        LEFT JOIN sy_goods_rush d ON d.id=a.gid
        LEFT JOIN sy_user e ON e.id=a.saler_id
        WHERE a.pay_state>-1 AND a.uid=?
        ORDER BY a.create_time DESC
        LIMIT ?,?";
        $sql_result = Db::query($sql, [$user_info['id'],  $limit, $page_size]);
        $sql_count = "SELECT COUNT(*) total_count FROM sy_user_order a  WHERE a.pay_state>-1 AND a.state=1 AND a.uid=?";
        $sql_count_result = Db::query($sql_count, [$user_info['id']]);
        $list = $sql_result;

        foreach ($list as &$v) {

            if ($v['pay_state'] == 0) {
                $v['stateStr'] = "待付款";
            } else if ($v['pay_state'] == 1) {
                $v['stateStr'] = "已付款";
            } else if ($v['pay_state'] == 2) {
                $v['stateStr'] = "已上架";
            }
            if($v['astate'] == -1){
                $v['stateStr'] = "已取消";
            }
        }
        $data = array(
            'page_index' => $page_index,
            'page_size' => $page_size,
            'total_count' => $sql_count_result[0]['total_count'],
            'list' => $list
        );
        $this->result_ok('ok', $data);
    }
    /**
     * 获取我的订单统计数据
     */
    public function getMyOrderInfo()
    {
        $user_info = $this->checkToken();
        $sql = "SELECT * FROM sy_user_order
                WHERE uid=? AND pay_state>-1 AND state=1";
        $sql_result = Db::query($sql, [$user_info['id']]);
        $data = array(
            'orders_total_price' => 0,
            'orders_total_count' => 0,
        );
        if (count($sql_result) > 0) {
            $data['orders_total_count'] = count($sql_result);
        }
        $sql1 = "SELECT SUM(g_price) orders_total_price FROM sy_user_order  WHERE uid=?  AND pay_state>-1 AND state=1";
        $sql_result1 = Db::query($sql1, [$user_info['id']]);
        if (count($sql_result1) > 0) {
            $data['orders_total_price'] = $sql_result1[0]['orders_total_price'];
        }
        $this->result_ok('ok', $data);
    }




    public function getFansOrderStatisticsByUser()
    {
//        $admin = session('admin');//
//        $uid =  $admin['uid'];
        $uid =  362245;
        // 考虑性能，数据量不大了时取出全部用户，在内存中操作"
        $sql = "SELECT id , nickname, level1_recommender, level2_recommender, roles FROM sy_user WHERE state > -1";
        $users = Db::query($sql, []);
        $uids[] = $uid;

        $uids = getRecursionUids($uids, $users);
        $sql = "SELECT a.*, b.code as '商品code', b.name as '商品name', c.nickname as '买方nickname', c.phone as '买方phone', c.avatar as '买方avatar', d.nickname as '卖方nickname', d.phone as '卖方phone', d.avatar as '卖方avatar' FROM sy_user_order a 
    INNER JOIN sy_goods_rush b ON a.gid=b.id
    LEFT JOIN sy_user c ON c.id=a.uid 
    LEFT JOIN sy_user d ON d.id=a.saler_id
    WHERE a.uid IN (" . implode(',', $uids) . " ) AND a.pay_state > -1 AND a.state > -1 ";
        //测试暂时把这个条件屏蔽 上线要打开
        //AND TO_DAYS(a.create_time) = TO_DAYS(NOW())";
        $results = Db::query($sql, []);
//       var_dump($results);die;
        $topUserStatics = array();
        foreach ($results as $rv){
            $topUser = [];
            if(!empty($rv) && !empty($rv['uid'])){
                $curKey = array_search($rv['uid'],array_column($users,'id'));
                $curUser = array();
                if(!empty($curKey)){
                    $curUser = $users[$curKey];
                }
                $roles = [];
                if(!empty($curUser) && !empty($curUser['roles'])){
                    $roles = json_decode($curUser['roles'],true);
                }
                // 只有非管理员有总销
                if (!in_array(1,$roles)) {
                    // 先从统计数据中取值
                    if (empty($topUserStatics[$rv['uid']])) {
                        $curLinks = [$rv['uid']];
                        $curLinks = getRecommendLinks($curLinks, $users);
                        $curTopUser =  array_filter($users, function ($item) use ($curLinks) {
                            if ($item['id'] == $curLinks[count($curLinks)-1]) {
                                return $item;
                            }
                        });
                        if(!empty($curTopUser)){
                            $curTopUser = array_pop($curTopUser);
                        }else{
                            $curTopUser = [];
                        }
                        // 避免重复计算，将数据缓存至统计数据中
                        $topUserStatics[$rv['uid']] = $curTopUser;
                        $topUser = $curTopUser;
                    }
                }
            }
            $rv['总销'] = $topUser;
        }
        $today_total = 0;
        foreach ($results as $v){
            $today_total += $v['g_price'];
        }
        $result_data = [
            'list'=>$results,
            'today_total'=>$today_total
        ];
        $data = [
            'code' => 0,
            'msg' => '请指定要查询的用户',
            'count' => 0,
            'data' => $result_data,
        ];
        $this->result_ok('ok',$data);
    }

}